<?php
/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/7/28
 * Time: 12:32
 */
namespace app\crontab\controller\article;

use app\common\library\CommonFun;
use app\common\model\article\JPushArticleModel;
use app\common\model\article\PublishArticleModel;
use app\common\model\coin\CoinRuntimeModel;
use app\common\model\pair\PairRuntimeModel;
use app\common\model\pushlog\JpushArriveUpSensorsModel;
use app\common\model\user\UserBaseModel;
use app\common\model\user\UserDevicesModel;
use app\common\model\user\UserPairModel;
use app\common\redis\WeChatPushArticleRepeatRedis;
use app\common\service\GeTuiService;
use app\common\service\swooleJobs\JpushArticleJobs;
use app\crontab\controller\CrontabCommon;
use app\common\service\PidFile;

/**
 * 文章push推送
 */
class Push extends CrontabCommon
{
    public function test()
    {
        echo "test";
    }

    /**
     * 推送文章
     */
    public function pushArticle() {
        if (!PidFile::createPidFile('pushArticle', 1)) {
            echo '进程已启动足够数量' . PHP_EOL;
            return;
        }

        // push文章推送表
        $JPushArticleModel = new JPushArticleModel();

        // 获取需要推送的文章列表
        $pushArticleList  = $JPushArticleModel->getPushList();

        $redisModel = WeChatPushArticleRepeatRedis::getInstance();
        $pair_runtime = PairRuntimeModel::getInstance();
        $user_devices_model = UserDevicesModel::getInstance();
        $JpushArticleJobs = new JpushArticleJobs();
//        $user_configure_model = UserConfigureModel::getInstance();
        foreach ( $pushArticleList as $data ) {
            // 更新状态为已推送
            $update = array(
                'is_push' => 1,
            );
            $JPushArticleModel->update_data($data['id'], $update);

            $jpush_id_list = array();
            $getui_id_list = array();

            $ios_count = 0;
            $android_count = 0;
            $user_id_list = array();

            if ( $data['coin_id'] != 0 ){
                // 获取推送币种下用户列表
                if ( $data['coin_id'] > 0 ){
                    $user_id_list = $pair_runtime->get_user_list_by_coin_id( $data['coin_id'] );
                    if ( !$user_id_list ){
                        continue;
                    }

                    $user_id_list = array_values( $user_id_list );

                    // 获取用户对应的推送id列表
                    $user_jpush_list = $user_devices_model->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $user_id_list ) ) );

                    if ( ! $user_jpush_list ){
                        continue;
                    }

                } else {
                    $user_jpush_list = $JPushArticleModel->get_not_follow_coin_getui_list();
                }

                foreach ( $user_jpush_list as $value ) {

                    if ( !$value['jpush'] && !$value['getui'] ){
                        continue;
                    }

                    if ( $value['getui'] ){
                        // 增加文章推送缓存
                        if ( $redisModel->getRepeatStr( $value['getui'], $data['article_id']) ){
                            // 检测3分钟内有推送
                            continue;
                        }
                    }


                    $redisModel->setRepeatStr( $value['getui'], $data['article_id']);

                    if ( !$value['getui'] ){
                        $jpush_id_list[] = $value['jpush'];
                    } else {
                        $getui_id_list[] = $value['getui'];
                        if ( $value['type'] == 'ios' ){
                            $ios_count ++;
                        } else {
                            $android_count ++;
                        }
                    }
                }
            }

            // 若没有推送列表则退出
            if ( !$jpush_id_list && !$getui_id_list && $data['coin_id'] != 0 ){
                continue;
            }

            $contentId = $JpushArticleJobs->push( $data, $getui_id_list );
            if ( $contentId ){
                $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
                $update['push_msg_id_list'] = $contentId;
                $update['push_count_ios'] = $ios_count;
                $update['push_count_android'] = $android_count;
                $update['coin_id'] = $data['coin_id'];
                $update['article_id'] = $data['article_id'];
                $update['push_user_id_list'] = json_encode( $getui_id_list );
                $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_ARTICLE;
                $update['content'] = CommonFun::json_encode2( $data );
                $JpushArriveUpSensorsModel->add_log( $update, $user_id_list , $data['coin_id'] == 0 ? 1 : 0 );
            }
        }
    }

    /**
     * 每天六点点定时推用户关注币种日报
     */
    public function user_pair_daily_push()
    {
        // 获取推送的uid_list
        $userBaseModel = UserBaseModel::getInstance();
        $pairRuntimeModel = PairRuntimeModel::getInstance();
        $userPairModel = UserPairModel::getInstance();

        $time = date( 'Y-m-d', time() - 86400 * 30 );
        if ( ENV == 'test' ){
            $where = array(
                'last_time' => array( 'gt', $time ),
                'getui'    => array( 'NEQ', ""),
            );
        } else {
            $where = array(
                'last_time' => array( 'gt', $time ),
                'getui'    => array( 'NEQ', ""),
            );
        }

        $list = $userBaseModel->where( $where )->join( "left join user_devices on user_base.id = user_devices.user_id" )->column("getui", "user_id" );

        $modelCoin = new CoinRuntimeModel();
        $where = [
            'status' => 1,
            'type' => 1,
            'sort' => array('gt', 0),
            'deleted' => -1,
        ];

        $coin_id_list = $modelCoin->search_id_list( $where, $page = 1, $asc = true, $sort_by = 'sort', $list_rows = 200 );

        $where = array(
            "push_time" => array( "gt", date( 'Y-m-d 00:00:00', time() - 86400 * 2 ) ),
            "coin_id"   => array( "in", $coin_id_list )
        );

        // 获取近三天发过PUSH的币种
        $JPushArticleModel = JPushArticleModel::getInstance();
        $on_push_coin_id_list = $JPushArticleModel->where( $where )->column( "coin_id" );
        $on_push_coin_id_list  = $on_push_coin_id_list ?: array();

        $btc_eth = array( 301, 617 );
        $on_push_coin_id_list = array_merge( $on_push_coin_id_list, $btc_eth );
        
        $coin_id_list = array_diff( $coin_id_list, $on_push_coin_id_list );

        $user_id_list = array_keys( $list );

        // 获取用户对应的pair_id_list
        $where = array(
            'user_id' => array( "in", $user_id_list ),
            'deleted' => -1,
            'status' => 1
        );

        $user_pair_list = $userPairModel->field( "user_id,pair_id" )->where( $where )->select();

        $user_pair_list = $user_pair_list ?: [];
        $pair_id_list_base = array_column( $user_pair_list, "pair_id" );

        $where = array(
            "id"  => array( "in", $pair_id_list_base ),
        );

        $pair_id_list = $pairRuntimeModel->get_key_value( "id", "base", $where );

        $user_coin_list = array();

        foreach ( $user_pair_list as $value ){
            if ( !isset( $pair_id_list [ $value['pair_id'] ] ) ){
                continue;
            }

            // 若改币种不在top200则退出
            if ( !in_array( $pair_id_list [ $value['pair_id'] ], $coin_id_list ) ){
                continue;
            }

            if ( !$user_coin_list[$value['user_id']] ){
                $user_coin_list[$value['user_id']] = array();
            }

            array_push( $user_coin_list[$value['user_id']], $pair_id_list [ $value['pair_id'] ] );
        }

        $user_list_by_coin_list = array();

        // 用户分组
        foreach ( $user_coin_list as $key => $value ){
            $value = array_unique( $value );

            sort( $value );
            $md5_key = md5( json_encode( $value ) );

            if ( !isset( $user_list_by_coin_list[$md5_key] ) ){
                $user_list_by_coin_list[$md5_key] = array(
                    "user_id_list" => array(),
                    "coin_id_list" => $value
                );
            }

            array_push( $user_list_by_coin_list[$md5_key]["user_id_list"] , $key );
        }

        foreach ( $user_list_by_coin_list as $key => $value ){
            JpushArticleJobs::userPairDailyPushJobs( array( "user_id_list" => $value['user_id_list'], "coin_id_list" => $value['coin_id_list'] ) );
            echo "设置用户的推送";
            var_dump( $value['user_id_list'] );
        }
    }

    /**
     * 推送市场报告
     */
    public function user_pair_market_report()
    {
        // 获取推送的uid_list
        $userBaseModel = UserBaseModel::getInstance();
        $pairRuntimeModel = PairRuntimeModel::getInstance();
        $userPairModel = UserPairModel::getInstance();

        $time = date( "Y-m-d H:i:s", time() - 86400 * 15 );

        $where = array(
            'last_time' => array( 'gt', $time ),
            'getui'    => array( 'NEQ', ""),
        );

        $list = $userBaseModel->where( $where )->join( "left join user_devices on user_base.id = user_devices.user_id" )->column( "user_id,getui" );

        $user_id_list = array_keys( $list );

//        $user_id_list = array( 142, 221 );

        // 获取用户对应的pair_id_list
        $where = array(
            'user_id' => array( "in", $user_id_list ),
            'deleted' => -1,
            'status' => 1
        );

        $user_pair_list = $userPairModel->field( "user_id,pair_id" )->where( $where )->select();
        $user_pair_list = $user_pair_list ?: [];
        $pair_id_list_base = array_column( $user_pair_list, "pair_id" );

        $where = array(
            "id"  => array( "in", $pair_id_list_base ),
        );

        $pair_id_list = $pairRuntimeModel->get_key_value( "id", "base", $where );

        $user_coin_list = array();

        foreach ( $user_pair_list as $value ){
            if ( !isset( $pair_id_list [ $value['pair_id'] ] ) ){
                continue;
            }

            if ( !$user_coin_list[$value['user_id']] ){
                $user_coin_list[$value['user_id']] = array();
            }

            array_push( $user_coin_list[$value['user_id']], $pair_id_list [ $value['pair_id'] ] );
        }

        $user_list_by_coin_list = array();

        // 用户分组
        foreach ( $user_coin_list as $key => $value ){
            $value = array_unique( $value );

            sort( $value );
            $md5_key = md5( json_encode( $value ) );

            if ( !isset( $user_list_by_coin_list[$md5_key] ) ){
                $user_list_by_coin_list[$md5_key] = array(
                    "user_id_list" => array(),
                    "coin_id_list" => $value
                );
            }

            array_push( $user_list_by_coin_list[$md5_key]["user_id_list"] , $key );
        }

        echo "可推送数据".count( $user_list_by_coin_list );
        $user_list_by_coin_list = array_chunk( $user_list_by_coin_list, 80 );

        $i = 0;
        foreach ( $user_list_by_coin_list as $value ){
            JpushArticleJobs::userPairMarketReportMqJobs( $value , $i * 60 );
            $i ++;
            echo "设置用户的推送{$i}".PHP_EOL;
        }
    }


    /**
     * BTC/ETH 定时推送行情资讯
     */
    public function market_information_push()
    {
        $PairRuntimeModel = PairRuntimeModel::getInstance();
        $PublishArticleModel = PublishArticleModel::getInstance();
        $UserPairModel = UserPairModel::getInstance();
        $JpushArticleJobs = new JpushArticleJobs();
        $where = array(
            "base"  => array( 'in', array( 301 ) ),
            "exchange" => "global",
            "quote"    => 2086,
            "status" => 1,
            "deleted" => -1
        );

        $pair_id_list = $PairRuntimeModel->get_key_value( "base", "id", $where );

        $pair_id_list = $pair_id_list ?: array();
        $userDevicesModel = new UserDevicesModel();                // 获取用户对应的推送id列表

        // 生成推送相关文章
        $article_id_list = $PublishArticleModel->createDataQuotation( array_keys( $pair_id_list ) );

        foreach ( $pair_id_list as $key => $value ){
            $article_info = $PublishArticleModel->get_data_by_id( $article_id_list[$key] );
            $where = array(
                "base"  => $key,
                "status" => 1,
                "deleted" => -1
            );

            // 获取该币种所有交易对信息
            $pair_value_id_list = $PairRuntimeModel->search_id_list_no_page( $where );
            $pair_value_id_list = $pair_value_id_list ?: array();

            $where = array(
                "pair_id" => array( "in", $pair_value_id_list ),
                "status"  => 1,
                "deleted" => -1
            );

            // 获取相关推送用户
            $user_id_list = $UserPairModel->get_key_value( "id", "user_id" , $where );

            $user_id_list = array_unique( $user_id_list );
            $user_jpush_list = $userDevicesModel->muti_get_data_by_where( array( 'user_id'=> array( 'in' , $user_id_list ) ) );

            $data_list = $JpushArticleJobs->get_push_list( $user_jpush_list );
            if ( !$data_list['getui_id_list'] ){
                return false;
            }

            $geTui = new GeTuiService();
            $contentId = $geTui->pushMessageToList( $data_list['getui_id_list'], $article_info['title'], $article_info['summary'], $PublishArticleModel->get_push_jump_url( $article_info['h5_url'] ,$article_info['id'] ),  300 * 1000 );

            // 记录推送数据
            if( $contentId ){
                $JpushArriveUpSensorsModel = JpushArriveUpSensorsModel::getInstance();
                $update['push_msg_id_list'] = $contentId;
                $update['push_count_ios'] = $data_list['ios_count'];
                $update['push_count_android'] = $data_list['android_count'];
                $update['coin_id'] = $key;
                $update['article_id'] = (int) $article_id_list[$key];
                $update['push_user_id_list'] = json_encode( $data_list['getui_id_list'] );
                $update['type'] = $JpushArriveUpSensorsModel::PUSH_TYPE_DAILY_TEST_PUSH;

                $update['content'] = '[]';
                $JpushArriveUpSensorsModel->add_log( $update, $data_list['user_id_list'] );
            }
        }

        return true;
    }













}